<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app">
      <a-tabs v-model:activeKey="data.activeKey">
        <a-tab-pane key="1"
          tab="概要">













          <a-row justify="space-between">
            <a-col :span="12">
              <a-space :size="20">
                <h2 style="display: inline">
                  <CaretLeftFilled @click="back()" />
                </h2>
                <h2 style="display: inline">采购暂收送检单</h2>
                <h3 style="display: inline">{{ data.form.id }} </h3>
                <a-space :size="12">
                  <a-button shape="circle">
                    {{ data.form.docStatus }}
                  </a-button>
                  <a-button shape="circle">
                    <LockOutlined />
                  </a-button>
                  <a-button shape="circle"
                    :type="data.form.approved ? 'primary' : 'default'">
                    <CheckOutlined />
                  </a-button>
                  <a-button shape="circle">
                    <FlagOutlined />
                  </a-button>

                  <a-button shape="circle"
                    @click="print()">

                    <PrinterOutlined />
                  </a-button>


                </a-space>
              </a-space>
            </a-col>
            <a-col :span="12">
              <a-row justify="end">
                <a-space :size="6"
                  v-if="!data.form.edit">
                  <a-button size="small"
                    type="primary"
                    @click="edit()"
                    v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved)">
                    <FormOutlined />
                    编辑
                  </a-button>
                  <a-button size="small"
                    type="primary"
                    danger
                    @click="del()"
                    v-if="data.form.docStatus === 'O' && !data.form.approved">
                    <DeleteOutlined />删除
                  </a-button>
                  <a-dropdown>
                    <a-button size="small"
                      v-if="!(data.form.docStatus === 'L')">更多操作
                      <DownOutlined />
                    </a-button>
                    <template #overlay>
                      <a-menu @click="more">
                        <a-menu-item key="a"
                          v-if="data.form.docStatus !== 'C'">关闭单据</a-menu-item>
                        <a-menu-item key="b"
                          v-if="data.form.docStatus === 'C'">打开单据</a-menu-item>

                        <a-menu-item key="c"
                          v-if="!data.form.approved">发起审核</a-menu-item>
                        <a-menu-item key="d"
                          v-if="data.form.approved">取消审核</a-menu-item>

                        <a-menu-item key="e">采购入库单</a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                  <a-button size="small"
                    @click="refresh">
                    <RetweetOutlined />
                    刷新
                  </a-button>
                </a-space>
              </a-row>
            </a-col>
          </a-row>



          <br />





          <a-form ref="formRef"
            :model="data.form"
            :rules="data.rules"
            :label-col="{ span: 4 }">
            <a-row class="smart-query-form-row">
              <a-col :span="6">
                <a-form-item label="部门"
                  name="deptId">
                  <DepartmentTreeSelect v-if="data.form.edit"
                    :init="false"
                    v-model:value="data.form.deptId"
                    @update:value="change" />
                  <span v-else>{{ data.form.deptName }}</span>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="制单">
                  <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
                </a-form-item>
                <a-form-item label="修改">
                  <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
                </a-form-item>
                <a-form-item label="备注">
                  <a-textarea v-if="data.form.edit"
                    v-model:value="data.form.remark"
                    :rows="1" />
                  <span v-else>{{ data.form.remark }}</span>
                </a-form-item>
              </a-col>
              <a-col :span="8"></a-col>
            </a-row>
          </a-form>

          <a-divider />
          <a-row>
            <a-button-group></a-button-group>

            <a-table style="width: 100%"
              :dataSource="data.form.lista"
              :columns="columnsa"
              rowKey="lineNum"
              :scroll="{ y: 700, x: 600 }"
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['20', '30', '40', '50', '100'],
                defaultPageSize: 20,
                showQuickJumper: true,
              }">
              <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'qty'">
                  <a-input-number size="small" v-if="record.edit"
                    style="width: 200px"
                    v-model:value="record.qty"
                    :step="0.0001"
                    :min="0.0001"
                    :max="record.maxQty"
                    @change="qtyChange(record)" />
                  <span v-else>{{ excute(text) }}</span>
                </template>

                

                <template v-if="column.dataIndex === 'quality'">
                  <a-select size="small" v-if="record.edit"
                    style="width: 100%"
                    v-model:value="record.quality"
                    name="quality"
                    default-value="D">
                    <a-select-option key="A">合格</a-select-option>
                    <a-select-option key="B">让步接收</a-select-option>
                    <a-select-option key="C">不合格</a-select-option>
                    <a-select-option key="D">检验中</a-select-option>
                  </a-select>
                  <span v-else>
                    <a-tag v-if="text === 'A'"
                      color="#00ff00">合格</a-tag>
                    <a-tag v-if="text === 'B'"
                      color="#ffaa00">让步接收</a-tag>
                    <a-tag v-if="text === 'C'"
                      color="#ff0000">不合格</a-tag>
                    <a-tag v-if="text === 'D'"
                      color="#00ff00">检验中</a-tag>
                  </span>
                </template>

                <template v-if="record.edit && column.dataIndex === 'action'">
                  <a-button size="small" @click="lineaDel(record)"
                    danger
                    type="link">
                    <DeleteOutlined />
                  </a-button>
                </template>
              </template>


              <template #expandedRowRender="{ record }">
                <a-app>
                  <a-table style="width: 100%"
                    :scroll="{ y: 600 }"
                    :dataSource="record.lista"
                    :columns="columnsaa"
                    rowKey="lineNum"
                    :pagination="false">
                    <template #bodyCell="{ text, record, column, index }">
                      <template v-if="column.dataIndex === 'reqQty'">
                        <span>{{ excute(text) }}</span>
                      </template>
                      <template v-if="column.dataIndex === 'invQty'">
                        <span>{{ excute(text) }}</span>
                      </template>

                      <template v-if="column.dataIndex === 'addQty'">
                        <a-input-number v-if="record.edit"
                          style="width: 100%"
                          v-model:value="record.addQty"
                          :step="0.0001"
                          :min="0.0001" />
                        <span v-else>{{ excute(text) }}</span>
                      </template>

                      <template v-if="column.dataIndex === 'qty'">
                        <span>{{ excute(text) }}</span>
                      </template>

                      <template v-if="column.dataIndex === 'source'">
                        <span>{{ text === '1' ? '自制' : '外购' }}</span>
                      </template>

                      <template v-if="column.dataIndex === 'action'">
                        <a-button-group>
                          <a-button type="link"
                            @click="showForm(record)">
                            <FormOutlined />
                          </a-button>
                          <a-button type="link"
                            @click="lineaDel(record)"
                            danger>
                            <DeleteOutlined />
                          </a-button>
                        </a-button-group>
                      </template>
                    </template>
                  </a-table>


                </a-app>
              </template>

            </a-table>


            <a-row style="margin-top: 20px">
              <a-col :span="24">
                <a-button-group v-if="data.form.edit">
                  <a-button @click="save()"
                    type="primary">保存</a-button>
                  <a-button @click="refresh"> 取消</a-button>

                </a-button-group>
              </a-col>
            </a-row>
          </a-row>
        </a-tab-pane>
        <a-tab-pane key="2"
          tab="凭证">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-card title="采购订单">
                <a-table style="width: 100%"
                  :dataSource="data.form.listb"
                  :columns="columnsb"
                  rowKey="lineNum"
                  :scroll="{ y: 650, x: 600 }"
                  :pagination="false">
                  <template #bodyCell="{ text, record, column }">
                    <template v-if="column.dataIndex === 'id'">
                      <a-button type="link"
                        @click="showForm(record, 'poorda')">{{ text }}</a-button>
                    </template>
                  </template>
                </a-table>
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card title="采购入库单">
                <a-table style="width: 100%"
                  :dataSource="data.form.listc"
                  :columns="columnsc"
                  rowKey="lineNum"
                  :scroll="{ y: 650, x: 600 }"
                  :pagination="false">
                  <template #bodyCell="{ text, record, column }">
                    <template v-if="column.dataIndex === 'id'">
                      <a-button type="link"
                        @click="showForm(record, 'stoorda')">{{ text }}</a-button>
                    </template>
                  </template>
                </a-table>
              </a-card>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </a-spin>
  <!--  <Approvord :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>-->
</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { message, Modal, Form } from 'ant-design-vue';
import { smartSentry } from '/src/lib/smart-sentry';
import { approvordApi } from '/src/api/business/erp/approvord-api';
import { useRouter, useRoute } from 'vue-router';
import DepartmentTreeSelect from '/src/components/system/department-tree-select/index.vue';
import Approvord from '/src/components/business/erp/approved.vue';
import { goodsApi } from '/src/api/business/goods/goods-api.js';

import { subordApi } from '/src/api/business/erp/subord-api';

import { stoordApi } from '/src/api/business/erp/stoord-api.js';
import { saordApi } from '/src/api/business/erp/saord-api.js';
import { excute } from '../../../../utils/numformat-util.js';
import { poordApi } from '/@/api/business/erp/poord-api.js';

const route = useRoute();
const router = useRouter();
const data = reactive({
  form: {
    id: 0,
    objId: '',
    absId: '',
    approved: false,
    docStatus: 'O',
    vendId: null,
    vendName: null,
    deptId: null,
    deptName: null,
    edit: false,
    lista: [],
    listb: [],
    listc: [],
  },
  radioGroup: null,
  rules: {
    deptId: [{ required: true, message: '请选择部门' }],
    macName: [{ required: true, message: '请输入设备名称' }],
    macAddress: [{ required: true, message: '请输入设备地址' }],
  },
  model: {
    absId: '',
  },
  doc: {
    tm: 'subord',
    tda: 'suborda',
  },
  editableData: {
    nowDate: null,
  },
  visible: {
    approvord: false,
  },
  approvedData: {
    baseEntry: null,
    tabName: null,
  },
  itemList: [],
  chooseLinea: null,
  activeKey: '1',
});
const columnsa = ref([
  {
    title: '行号',
    dataIndex: 'lineNum',
    align: 'center',
    width: 80,
  },
  {
    title: '行状态',
    dataIndex: 'lineStatus',
    align: 'center',
    width: 80,
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 250,
    align: 'left',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'left',
  },
  {
    title: '规格',
    dataIndex: 'specs',
    width: 200,
    align: 'left',
    ellipsis: true,
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 250,
    align: 'right',
  },
  {
    title: '单位',
    dataIndex: 'unit',
    width: 120,
    align: 'center',
  },
  {
    title: '系统批次',
    dataIndex: 'batchId',
    width: 160,
    align: 'center',
  },
  {
    title: '质量状态',
    dataIndex: 'quality',
    width: 160,
    align: 'center',
  },

  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 160,
  },
]);


const columnsaa = ref([
  {
    title: '行号',
    dataIndex: 'lineNum',
    align: 'center',
    width: 80,
  },
  {
    title: '行状态',
    dataIndex: 'lineStatus',
    align: 'center',
    width: 80,
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 250,
    align: 'left',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'left',
  },
  {
    title: '规格',
    dataIndex: 'specs',
    width: 200,
    align: 'left',
    ellipsis: true,
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 250,
    align: 'right',
  },
  {
    title: '单位',
    dataIndex: 'unit',
    width: 120,
    align: 'center',
  },
  {
    title: '系统批次',
    dataIndex: 'batchId',
    width: 160,
    align: 'center',
  },
  {
    title: '质量状态',
    dataIndex: 'quality',
    width: 160,
    align: 'center',
  },

  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 160,
  },
]);



const columnsb = ref([
  {
    title: '基础编码',
    dataIndex: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '基础行号',
    dataIndex: 'lineNum',
    width: 250,
    align: 'right',
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 300,
    align: 'right',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'right',
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 120,
    align: 'right',
  },
]);
const columnsc = ref([
  {
    title: '目标编码',
    dataIndex: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '目标行号',
    dataIndex: 'lineNum',
    width: 250,
    align: 'right',
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 300,
    align: 'right',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'right',
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 120,
    align: 'right',
  },
]);
const tableLoading = ref(false);
const formRef = ref(null);

// 初始化
function init() {
  if (route.query.type === 'info') {
    data.form.id = route.query.id;
    queryData();
  } else if (route.query.type === 'tager') {
    poordApi
      .infoUnexecute(route.query.id)
      .then((res) => {
        // 主表

        data.form.deptId = res.data.deptId;
        data.form.deptName = res.data.deptName;

        // 明细
        res.data.lista.forEach((item) => {
          data.form.lista.push({
            id: data.form.id,
            lineNum: data.form.lista.length + 1,
            lineStatus: 'O',
            qty: item.qty,
            specs: item.specs,
            unit: item.unit,
            itemId: item.itemId,
            itemName: item.itemName,
            baseId: item.id,
            baseLineNum: item.lineNum,
            tax: 1.13,
            price: 0,
            priceLine: 0,
            taxPrice: 0,
            taxPriceLine: 0,
            quality: 'D',
            edit: true,
            maxQty: item.qty,
          });
        });
      })
      .finally(() => { });
    data.form.edit = true;
  } else {
    data.form.edit = true;
  }
}

// 更多操作
function more({ key }) {
  // 审核处理函数
  if (key === 'a') {
    data.form.docStatus = 'C';
    tableLoading.value = true;
    subordApi.update(data.form).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  } else if (key === 'b') {
    data.form.docStatus = 'O';
    tableLoading.value = true;
    subordApi.update(data.form).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  } else if (key === 'c') {
    approvordApi
      .add({
        id: 0,
        approvLineNum: 2,
        approvType: 'A',
        baseEntry: data.form.id,
        tabName: data.form.objName,
        docStatus: 'O',
        tabId: data.form.objId,
        baseVersion: data.form.version,
      })
      .then((res) => {
        queryData();
      });
  } else if (key === 'd') {
    approvordApi
      .add({
        id: 0,
        approvLineNum: 2,
        approvType: 'B',
        baseEntry: data.form.id,
        tabName: data.form.objName,
        docStatus: 'O',
        tabId: data.form.objId,
        baseVersion: data.form.version,
      })
      .then((res) => {
        queryData();
      });
  } else if (key === 'e') {
    router.push({ path: 'stoorda', query: { type: 'tager', id: data.form.id } });
  }
}

function save() {
  formRef.value
    .validate()
    .then(() => {
      tableLoading.value = true;
      if (data.form.id) {
        subordApi
          .update(data.form)
          .then((res) => {
            queryData(data.form.id);
            message.success('修改成功！');
          })
          .finally(() => {
            tableLoading.value = false;
          });
      } else {
        subordApi
          .add(data.form)
          .then((res) => {
            data.form.id = res.data;
            message.success('保存成功！');
            router.push({ path: data.doc.tda, query: { type: 'info', id: res.data } });
            queryData(res.data);
          })
          .finally(() => {
            tableLoading.value = false;
          });
      }
    })
    .catch((err) => {
      message.error('页面校验失败！');
    });
}

function edit() {
  data.form.edit = true;

  data.form.lista.forEach((item) => {
    item.edit = true;
  });
}

function del() {
  Modal.confirm({
    content: `确认删除（${data.form.id}）`,
    onOk() {
      subordApi.delete(data.form.id).then((res) => {
        message.success('删除成功！');
        router.push({ path: data.doc.tm });
      });
    },
    cancelText: '取消',
    onCancel() {
      Modal.destroyAll();
    },
  });

}

async function queryData() {
  tableLoading.value = true;
  formRef.value.resetFields();
  try {
    let queryResult = await subordApi.info(data.form.id);
    data.form = queryResult.data;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

function refresh() {
  queryData();
}

function back() {
  router.push({ path: data.doc.tm });
}

function change(item, key) {
  data.form.deptName = key;
}

// 审核------------------------------------------------------------------------------------------------
function approved() {
  data.approvedData.baseEntry = data.form.id;
  data.approvedData.tabName = data.form.objName;
  data.visible.approvord = true;
}

function onclose() {
  data.visible.approvord = false;
  queryData();
}

// 行----------------------------------------------a-------------------------------------------------------

function qtyChange(item) {
  item.priceLine = (item.qty * item.price).toFixed(4);
  item.taxPriceLine = (item.taxPrice * item.tax * item.qty).toFixed(4);
}

function queryItemList() {
  goodsApi
    .queryGoodsList({
      pageNum: 1,
      pageSize: 10,
    })
    .then((res) => {
      data.itemList = res.data.list;
    })
    .catch((err) => { })
    .finally(() => { });
}

function lineaEdit(key) {
  key.edit = true;
}

function lineaAdd() {
  data.form.lista.push({
    id: data.form.id,
    lineNum: data.form.lista.length + 1,
    lineStatus: 'O',
    qty: 1,
    quantity: 'A',
    edit: true,
  });
}

function lineaDel(item) {
  data.form.lista.splice(item.lineNum - 1, 1);
  for (let i = item.lineNum - 1; i < data.form.lista.length; i++) {
    data.form.lista[i].lineNum = data.form.lista[i].lineNum - 1;
  }
}

// --------------------------------凭证

function showForm(data, it) {
  router.push({ path: it, query: { type: 'info', id: data.id } });
}

onMounted(() => {
  init();
  queryItemList();
});
</script>
